package com.lagou.mvc.framework.util;

import com.lagou.mvc.framework.annotation.Controller;
import com.lagou.mvc.framework.annotation.RequestMapping;
import com.lagou.mvc.framework.annotation.Security;
import com.lagou.mvc.framework.pojo.BeanDefinition;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName BeanDefinitionUtil
 * @Description
 * @Author playboy
 * @Date 2021/4/29 4:53 下午
 * @Version 1.0
 **/
public class BeanDefinitionUtil {

	/**
	 * 解析class
	 *
	 * @param classes
	 * @return
	 */
	public static Map<String, BeanDefinition> createBeanDefinition(List<Class<?>> classes) {
		Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
		for (Class<?> aClass : classes) {
			if (aClass.isAnnotationPresent(Controller.class)) {
				//@Controller
				BeanDefinition beanDefinition = new BeanDefinition();
				Controller controller = aClass.getAnnotation(Controller.class);
				String controllerValue = controller.value();
				if (controllerValue.equals("")) {
					controllerValue = getFirstLower(aClass.getSimpleName());
				}
				beanDefinition.setId(controllerValue);
				beanDefinition.setClazz(aClass);
				if (aClass.isAnnotationPresent(RequestMapping.class)) {
					RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class);
					String requestMappingValue = requestMapping.value();
					if (!requestMappingValue.equals("")) {
						beanDefinition.setBashUrl(requestMappingValue);
					}
				}
				if (aClass.isAnnotationPresent(Security.class)) {
					Security security = aClass.getAnnotation(Security.class);
					String[] value = security.value();
					if (value != null) {
						List<String> users = Arrays.asList(value);
						beanDefinition.setUsers(users);
					}
				}
				beanDefinitionMap.put(beanDefinition.getId(), beanDefinition);
			}
		}
		return beanDefinitionMap;
	}

	private static String getFirstLower(String target) {
		if (target == null || target.equals("")) {
			return target;
		}
		return target.substring(0, 1).toLowerCase() + target.substring(1);
	}
}
